package com.sikan.dragdemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements ViewListener {


    public static Bitmap mergeBitmap;

    private ConstraintLayout layout;
    private ImageView image;

    private boolean permission;

    private boolean pic1;
    private boolean pic2;

    private ControlMaskImageView view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        title();
        layout = findViewById(R.id.layout);
        image = findViewById(R.id.iv);

        findViewById(R.id.btn1).setOnClickListener(v -> {
            if (!permission) {
                getPermissions();
                return;
            }
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, 10001);
        });
        findViewById(R.id.btn2).setOnClickListener(v -> {
            if (!permission) {
                getPermissions();
                return;
            }
            if(!pic1){
                Toast.makeText(MainActivity.this, "先选底图", Toast.LENGTH_SHORT).show();
                return;
            }
            if(pic2){
                Toast.makeText(MainActivity.this, "已有插图", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, 10002);
        });
        getPermissions();

    }

    private void title() {
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
        );
        View mActionBarView =
                LayoutInflater.from(this).inflate(R.layout.layout_actionbar, null);

        ImageView backView = mActionBarView.findViewById(R.id.tv_back);
        backView.setOnClickListener(v -> finish());
        TextView rightMenu = mActionBarView.findViewById(R.id.tv_back_gone);
        rightMenu.setOnClickListener(v -> {
            if(view!=null){
                view.setOutHide();
            }

            Bitmap bit=getViewBitmap(layout);

            String path=FileUtil.saveBitmap("img_"+ System.currentTimeMillis() +".jpg",bit,MainActivity.this);
            Toast.makeText(MainActivity.this,"保存文件到："+path,Toast.LENGTH_LONG).show();

//            Glide.with(MainActivity.this).load(path)
//                    .into(image);
        });

        Objects.requireNonNull(getSupportActionBar()).setCustomView(mActionBarView, lp);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }


    /**
     * 根据view来生成bitmap图片，可用于截图功能
     */
    public static Bitmap getViewBitmap(View v) {
        v.clearFocus(); //
        v.setPressed(false); //
        // 能画缓存就返回false
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }

    private void getPermissions() {
        XXPermissions.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        permission = true;
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        OnPermissionCallback.super.onDenied(permissions, never);
                        Toast.makeText(MainActivity.this, "请给权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = FileUtils.Companion.getPath(MainActivity.this, uri);
                if (path != null) {
                    pic1=true;
                    Glide.with(MainActivity.this).load(path)
                            .into(image);
                }
            }
        } else if (requestCode == 10002 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = FileUtils.Companion.getPath(MainActivity.this, uri);
                if (path != null) {
                    Bitmap bitmap = FileUtil.getBitmapFromFile(path,300,300);

                    ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                            ActionBar.LayoutParams.MATCH_PARENT,
                            ActionBar.LayoutParams.MATCH_PARENT,
                            Gravity.CENTER
                    );
                    view=new ControlMaskImageView(MainActivity.this);
                    layout.addView(view,1,lp);
                    view.setListener(this);
                    view.setBitmap(bitmap);
                    pic2=true;
                }
            }
        }
    }


    @Override
    public void delete() {
        pic2=false;
    }
}
